﻿using ActUtlTypeLib;

namespace SanLingPlc
{
    public class MySanLing
    {
        private ActUtlType actUtlType;

        public void Open_Plc(int station_No)
        {
            actUtlType = new ActUtlType();
            actUtlType.ActLogicalStationNumber = station_No;

            bool if_ok = false;
            for (int i = 0; i < 10; i++)
            {
                int connresult = actUtlType.Open();
                if (connresult == 0)
                {
                    if_ok = true;
                    break;
                }

            }
            if (!if_ok)
            {
                throw new System.Exception("连接三菱PLC失败，请检查相关参数及硬件！");
            }
        }

        /// <summary>
        /// 断开连接
        /// </summary>
        public void Close_Plc()
        {
            if (actUtlType != null)
                actUtlType.Close();
        }
        /// <summary>
        /// 读取D地址
        /// </summary>
        /// <param name="d_str">地址开头（如D100）</param>
        /// <param name="_length">读取长度</param>
        /// <returns></returns>
        public short[] read_d_arr(string d_str, int _length)
        {

            int[] mi = new int[_length];
            if (actUtlType != null && _length > 0)
                actUtlType.ReadDeviceBlock(d_str, _length, out mi[0]);
            return i_s(mi);
        }
        /// <summary>
        /// 读取D（单个）
        /// </summary>
        /// <param name="d_str">地址开头（如D100）</param>
        /// <returns></returns>
        public short read_d(string d_str)
        {
            int result;
            if (actUtlType != null)
                actUtlType.GetDevice(d_str, out result);
            else result = 0;
            return (short)result;
        }
        /// <summary>
        /// 用数组的方式设置D地址
        /// </summary>
        /// <param name="d_str">D地址开头</param>
        /// <param name="arr_data">所有D数据</param>
        public void Set_d_arr(string d_str, int[] arr_data)
        {
            if (actUtlType != null && arr_data.Length > 0)
                actUtlType.WriteDeviceBlock(d_str, arr_data.Length, ref arr_data[0]);
        }
        /// <summary>
        /// 把int类型转换成short类型（防止dll外部读出错误的类型）
        /// </summary>
        /// <param name="vs">int类型数组</param>
        /// <returns></returns>
        private short[] i_s(int[] vs)
        {
            short[] shortArray = new short[vs.Length];
            for (int i = 0; i < vs.Length; i++)
            {
                shortArray[i] = (short)vs[i];
            }
            return shortArray;
        }

    }
}
